package yeliuhuishi.averageScore;

import org.apache.hadoop.conf.Configuration;
import org.apache.hadoop.fs.Path;
import org.apache.hadoop.io.IntWritable;
import org.apache.hadoop.io.LongWritable;
import org.apache.hadoop.io.Text;
import org.apache.hadoop.mapreduce.Job;
import org.apache.hadoop.mapreduce.Mapper;
import org.apache.hadoop.mapreduce.Reducer;
import org.apache.hadoop.mapreduce.lib.input.FileInputFormat;
import org.apache.hadoop.mapreduce.lib.input.TextInputFormat;
import org.apache.hadoop.mapreduce.lib.output.FileOutputFormat;
import org.apache.hadoop.mapreduce.lib.output.TextOutputFormat;
import yeliuhuishi.File.DelAllFile;

import java.io.File;
import java.io.IOException;
import java.util.StringTokenizer;
import java.util.concurrent.atomic.AtomicInteger;

/**
 * 统计三个数据，计算平均数
 * avg
 */

public class AvgSource extends Configuration {

    public static void main(String[] args) throws Exception {
        String input = "src/main/java/yeliuhuishi/averageScore/input";
        String output = "src/main/java/yeliuhuishi/averageScore/output";

        DelAllFile.delAllFile(new File(output));
        Configuration conf = new Configuration();

        Job job = Job.getInstance(conf, AvgSource.class.getName());

        job.setJobName("AvgSource");

        job.setMapperClass(Map.class);
        job.setReducerClass(Reduce.class);
        job.setJarByClass(AvgSource.class);

        job.setOutputKeyClass(Text.class);
        job.setOutputValueClass(IntWritable.class);

        job.setInputFormatClass(TextInputFormat.class);
        job.setOutputFormatClass(TextOutputFormat.class);

        FileInputFormat.setInputPaths(job, new Path(input));
        FileOutputFormat.setOutputPath(job, new Path(output));


        System.out.println(job.waitForCompletion(true) ? "成功" : "失败");

    }

    public static class Map extends Mapper<LongWritable, Text, Text, IntWritable> {
        @Override
        protected void map(LongWritable key, Text value, Context context) throws IOException, InterruptedException {
            StringTokenizer tokenizer = new StringTokenizer(value.toString());
            while (tokenizer.hasMoreElements()) {
                String strName = tokenizer.nextToken();
                String strSource = tokenizer.nextToken();
                context.write(new Text(strName), new IntWritable(Integer.parseInt(strSource)));
            }
        }
    }

    public static class Reduce extends Reducer<Text, IntWritable, Text, IntWritable> {
        @Override
        protected void reduce(Text key, Iterable<IntWritable> values, Context context) throws IOException, InterruptedException {

            AtomicInteger sum = new AtomicInteger();
            AtomicInteger num = new AtomicInteger();
            for (IntWritable value : values) {
                sum.addAndGet(value.get());
                num.getAndIncrement();
            }
            context.write(key, new IntWritable((sum.get() / num.get())));
        }
    }

}
